How to upgrade PHP script from MySQL to MySQLi

(Originally posted on my Portuguese blog at rberaldo.com.br)

Updating to MySQLi is not just adding an extra “i” to function calls like mysql_connect or mysql_query, as many people say.

However, it’s not very complicated either. You just need to be careful with the parameters of each function.

In this article, I will show you how to update your PHP scripts from MySQL to MySQLi.

The Reason

As I mentioned in this article, the mysql library is outdated.

This means you should not use functions like mysql_connect, mysql_query, and similars.

Instead, you should use mysqli_connect and mysqli_query.

But the difference is not just the extra “i” in the function name. The list of parameters is usually a bit different, so we need to pay attention to that.

MySQLi or PDO?

Personally, I recommend and prefer PDO. But there’s a small problem…

PDO requires some knowledge of Object-Oriented Programming (OOP). And I know that many beginners have a hard time with that.

So, I’ll show you here how to use mysqli in a procedural way, that is, how to use it with function calls instead of using the mysqli class and its methods and properties.

Why It’s Not as Simple as They Say

There are many people out there saying that you just need to add the “i” to the function calls, and you’re good to go.

It’s not that simple.

Many MySQLi functions have additional parameters, a different order, and so on.

The mysql_* functions didn’t require the connection identifier parameter (the value returned by mysql_connect). They always looked for an active connection.

With mysqli, it’s different…

It’s essential to provide the connection identifier.

This way, we can have multiple connections in the same script without the risk of conflicts or unexpected behavior.

That’s just one example.

We’ll look at this in more detail in practice shortly.

Example Database

Let’s create a simple database for our tests.

CREATE TABLE employees(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(80) NOT NULL,
    salary DECIMAL(10,2) NOT NULL,
    birthdate DATE NOT NULL,
    PRIMARY KEY (id)
) COLLATE=utf8_unicode_ci;

Let’s insert some data:

INSERT INTO employees(name, email, salary, birthdate) VALUES
('Ana', '[email protected]', 1400.00, '1993-10-16'),
('Daniela', '[email protected]', 1380.50, '1996-05-15'),
('João', '[email protected]', 1400.00, '1995-11-10'),
('Julia', '[email protected]', 1200.95, '1997-03-22'),
('Sabrina', '[email protected]', 1800.57, '1990-12-03'),
('Paulo', '[email protected]', 1750.43, '1991-06-25');

Displaying Data Using MySQL

Let’s create a simple script to display all the data using mysql_* functions.

// connection credentials
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db   = 'db_name';
 
// connection to the database
$con = mysql_connect($host, $user, $pass);
 
// selecting the database
mysql_select_db($db);
 
// execute the query
$sql = "SELECT * FROM employees ORDER BY name";
$res = mysql_query($sql);
 
// total of results
$total = mysql_num_rows($res);
 
echo "total of results: " . $total . "<br>";
 
// loop through results
while ($f = mysql_fetch_array($res)) {
    echo $f['name'] . " | " . $f['email'] . " | " . $f['salary'] . " | " . date('d/m/Y', strtotime($f['birthdate'])) . "<br>";
}
 
// close the connection
mysql_close();

The script is super simple, just a SELECT that lists the records from the table, along with the total number of records.

Displaying Data Using MySQLi

Now, let’s rewrite the previous script using MySQLi. I’ll provide the code and then discuss the key details.

$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db   = 'db_name';
 
// connecting...
$con = mysqlI_connect($host, $user, $pass, $db);
 
// query
$sql = "SELECT * FROM employee ORDER BY name";
$res = mysqli_query($con, $sql);
 
// total of results
$total = mysqli_num_rows($res);
 
echo "total of results: " . $total . "<br>";
 
// loop through results
while ($f = mysqli_fetch_array($res)) {
    echo $f['name'] . " | " . $f['email'] . " | " . $f['salary'] . " | " . date('d/m/Y', strtotime($f['birthdate'])) . "<br>";
}
 
// close the connection
mysqli_close($con);

You can notice three main differences:

  1. mysqli_connect allows you to connect to MySQL and select the database in one step. You don’t need to use mysqli_select_db.
  2. The first parameter of mysqli_query is not the SQL query string, as it was with mysql_query. Now, you need to pass the connection identifier (returned by mysqli_connect) and then the SQL query string.
  3. mysqli_close requires the parameter that identifies the connection. In contrast, for mysql_close, it was optional.

As you can see, just adding the “i” doesn’t solve everything 100%. Some minor modifications are still necessary.

Parameter Lists

Did you notice some differences in these simple scripts?

These differences become more significant if you’re using other functions, like mysql_affected_rows, mysql_real_escape_string, and some others.

I recommend that you check the documentation for each of them and pay attention to the parameter lists for each.

See what the order is, which ones are mandatory, and which ones are optional.

I’ll leave the links to the documentation here:

MySQL Function List

MySQLi Function List

Just so you understand better, parameters in square brackets are optional. resource is the return type of mysql_connect and mysql_query. mysqli is the connection identifier returned by mysqli_connect, and mysqli_result is the return type of mysqli_query.

With this information, you’ll have a better understanding of the parameters that each function requires.

Related posts

13 Thoughts to “How to upgrade PHP script from MySQL to MySQLi”

  1. Blood Nick

    Olá, estou com um problema: “Deprecated: mysql_pconnect(): The mysql extension is drprecated and will be removed in future: use mysqli or PDO instead in C:\wamp\www\Pixels\Connections\pixels_conexao.php on line 9”.

    E código do pixels_conexao.php é:

    “”

    1. Falo sobre isso neste artigo: http://rberaldo.com.br/mysql-obsoleto-php/
      Você deve usar MySQLi ou PDO em vez da extensão mysql

    1. Oliveira Neilde

      Muitíssimo Obrigada. Deu certo consegui!

  2. Oliveira Neilde

    Olá eu entendi como funciona o mysqli se eu colocar a conexao no mesmo arquivo que contém os selects. Porém não consigo fazer com várias páginas com selects e um include conexao.php… o que acontece? não sei definir uma variável que seja compartilhada em todas as páginas que contenham o include. Trata-se da variavel $con no exemplo. Não sei mexer com classes ainda e minha noção de OOP é quase nula. Pode ajudar?

    1. Olá.
      Em vez de criar uma variável global, sugiro criar uma função que abre a conexão e retorna o link.
      É a mesma ideia da função db_connect() que criei neste artigo: http://blog.ultimatephp.com.br/sistema-de-login-php/

      1. Oliveira Neilde

        Muitíssimo Obrigada. Deu certo consegui!

  3. Pela primeira vez consegui compreender exatamente a mudança.
    Muito obrigado pelo artigo.

    1. Que bom que conseguiu entender! 🙂

  4. Rogerio Oliveira

    Olá Beraldo,
    Parabéns pelo seu trabalho.
    Vamos lá.
    Sou novato no PHP e estou tendo uma dificuldade no uso do comando SQL Select simples quando for a leitura apenas de um único registro acessando com a chave primária da tabela de Usuário. Vou exemplificar: Num Loop While para a confecção de uma lista de Pessoas, onde o comando SQL Select abriu uma leitura com vários registros, para cada registro de Pessoa necessito fazer um outro comando Select usando a chave primária, caso a Pessoa já tenha um Usuário cadastrado.
    Meu ambiente é XAMP e uso o MySQL.

    Numa lista de Pessoas que acessam o sistema, gostaria de identificar quem já tem a identificação de usuário no sistema.

    A seguir o código da minha ultima tentativa: Ele faz a lista só que ainda não consegui acessar dados da tabela de usuário num acesso a um único registro.

    $query1 = (“Select
    P.IdPessoa
    , P.IdCliente
    , P.IdUsuarioPessoa
    , P.Nome
    , P.TipoPessoal
    , P.Sexo
    , P.Email
    , P.Cpf
    , C.IdCliente
    , C.SiglaCliente
    FROM pessoa P
    , cliente C
    WHERE ” . $ClausulaWHERE . ” order by
    P.Nome
    , P.TipoPessoal
    , P.Sexo
    , P.Email
    , P.Cpf; ” );

    mysqli_stmt_bind_result($stmt, $idpessoa, $idclientep, $idusuario, $nome, $tipopessoal, $sexo, $email, $cpf, $idcliente, $siglacliente);
    // CARREGA AS PESSOAS SELECIONADAS
    if ($stmt = mysqli_prepare($conn, $query))
    {
    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */

    // ELABORA LISTA DE PESSOA SEJA DO CLIENTE OU DA INSTITUIÇÃO
    while (mysqli_stmt_fetch($stmt))
    {
    $contador++;

    // Verifica se Pessoa já tem usuário cadastrado
    if ($idusuario > 0 )
    {
    $query3 = mysqli_query($conn,”SELECT
    IdUsuario
    , SiglaUsuario
    , TipoUsuario
    , UsuarioAutorizado
    FROM usuario
    WHERE IdUsuario = $idusuario “);

    // output data of each row
    $row = mysqli_fetch_assoc($query3)

    $idusuario = $row[“IdUsuario”];
    $siglausuario = $row[“SiglaUsuario”];
    $tipousuario = $row[“TipoUsuario”];

    1. Não é bom fazer consultas dentro de loops. Isso gera o que chamamos de Problema do N + 1. O correto é usar JOIN ou subquery.
      Falo sobre isso neste artigo: http://rberaldo.com.br/o-problema-do-n-mais-1/

  5. Adriano Santos

    Olá,

    Estou iniciando o trabalho com script php, e de certa forma estou com dificuldades neste início…. fiz alguma alterações no meu scrip, como orientado inserindo o “i” no MySql… mas ainda está apresentando erro… será que alguém pode me dar uma luz, o que fazer? E como fazer… (segue o erro)

    Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given in /home/sitev846/public_html/pizza/config/conexao.php on line 19

    Warning: mysqli_error() expects exactly 1 parameter, 0 given in /home/sitev846/public_html/pizza/config/conexao.php on line 19

    1. Olá.
      Atualizar para MySQLi **NÃO** é apenas colocar um “i” a mais nas chamadas de funções como mysql_connect ou mysql_query, como muitos dizem..
      Sugiro que releia o artigo e baixe o meu guia gratuito. Explico passo-a-apasso como migrar para MySQLi

Leave a Comment